﻿using UnityEngine;

namespace VCity
{
    public class AdsInteractor : MonoBehaviour
    {
        public Transform origin;

        #region Unity Methods
        private void OnValidate()
        {
            if (origin == null)
            {
                var ctrl = GetComponent<CharCtrl>();
                if (ctrl != null)
                    origin = ctrl.followTransform;
            }
        }

        private void OnDestroy()
        {
            // ui
            var ui = UIMain.Instance;
            if (ui != null)
                ui.handIcon.SetActive(false);
        }

        private void Update()
        {
            CheckAdsCollision();
        }
        #endregion

        void CheckAdsCollision()
        {
            Transform tr = this.origin;

            if (tr == null)
            {
                var cam = Camera.main;
                tr = cam.transform;
            }

            float distance = AdsBoardManager.Instance.interactDistance;

            Debug.DrawLine(tr.position, tr.position + tr.forward * distance, Color.red);
            var ui = UIMain.Instance.handIcon.gameObject;
            AdsInteractable target = null;
            if (Physics.Raycast(tr.position, tr.forward, out var hit, distance, PhysicsSettings.Instance.adsLayer))
            {
                Debug.DrawLine(hit.point, hit.point + hit.normal * 1, Color.green);
                target = hit.collider.GetComponent<AdsInteractable>();
            }
            ui.SetActive(target != null && target.HasHypperLink);

            // Click event
            if (target != null && InputMain.Instance.playerInput.actions["AdsInteract"].triggered)
                target.OnClick();
        }
    }
}